import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(request: NextRequest) {
  try {
    if (request.method !== 'GET') return NextResponse.next();
    const appUrl = process.env.APP_URL;
    if (!appUrl) throw new Error('env var APP_URL not existed');
    const res = await fetch(`${appUrl}/api/edge-auth`, {
      headers: request.headers,
    });
    const session = await res.json();
    const path = request.nextUrl.pathname;
    if (!session && !path.startsWith('/login'))
      return NextResponse.redirect(new URL('/login', request.url));
    if (session?.user?.role === 'admin' && !path.startsWith('/admin'))
      return NextResponse.redirect(new URL('/admin', request.url));
    if (session?.user?.role === 'shop' && !path.startsWith('/shop'))
      return NextResponse.redirect(new URL('/shop', request.url));
    if (
      session?.user?.role === 'user' &&
      ['/admin', '/shop', '/login'].some((p) => path.startsWith(p))
    )
      return NextResponse.redirect(new URL('/', request.url));
  } catch (error) {
    console.error(error);
    return NextResponse.redirect(new URL('/error-page', request.url));
  }
}

export const config = {
  matcher:
    '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|error-page|socket.io).*)',
};
